package com.zyj.test.month2.day2;

/**
 * @author Yijia Zhang
 * @create 2024-11-21 22:30
 */
public class Code0005 {

    public String longestPalindrome(String s) {
        int len = s.length();
        int idx1 = 0;
        String maxStr = "";
        String tmp = "";
        while (idx1 < len) {
            int idx2 = idx1 + 1;
            if (idx2 < len && s.charAt(idx2) == s.charAt(idx1)) {
                tmp = longestSubString(idx1, idx2, s);
                if (tmp.length() > maxStr.length()) {
                    maxStr = tmp;
                }
            }
            tmp = longestSubString(idx1, idx1, s);
            if (tmp.length() > maxStr.length()) {
                maxStr = tmp;
            }
            idx1++;
        }
        return maxStr;
    }

    private String longestSubString(int idx1, int idx2, String s) {
        if (s.charAt(idx1) != s.charAt(idx2)) {
            return String.valueOf(s.charAt(idx1));
        }
        int l = idx1, r = idx2;
        int max = 1;
        String maxStr = String.valueOf(s.charAt(idx1));
        while (l >= 0 && r <= s.length() - 1 && s.charAt(l) == s.charAt(r)) {
            if ((r - l + 1) > max ) {
                max = r - l + 1;
                maxStr = s.substring(l,r+1);
            }
            l--;
            r++;
        }
        return maxStr;
    }
}
